package com.easou;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo {
	
	private final Lock lock = new ReentrantLock();
	private final Condition oddCondition = lock.newCondition();
	
	public class Count {
		private int num;
		
		public int getNum(){
			return num;
		}
		
		public void setNum(int num){
			 this.num = num;
		}
	}
	
	public class Print implements Runnable{
		
		private Count count;
		
		public Print(Count count){
		   this.count = count;
		}

		@Override
		public void run() {
			while(count.getNum() < 9){
				lock.lock();
				try {
					if((count.getNum()&1) == 1 && count.getNum() != 0){
						oddCondition.wait();
					}
					count.setNum(count.getNum()+1);
					System.out.println("Print1:"+count.getNum());
					oddCondition.notify();
				} catch (Exception e) {
					// TODO: handle exception
				}finally{
					lock.unlock();
				}
			}
		}
		
	}
	
public class Print2 implements Runnable{
		
		private Count count;
		
		public Print2(Count count){
		   this.count = count;
		}

		@Override
		public void run() {
			while(count.getNum() < 10){
				lock.lock();
				try {
					if((count.getNum()&1) == 0){
						oddCondition.wait();
					}
					count.setNum(count.getNum()+1);
					System.out.println("Print2:"+count.getNum());
					oddCondition.notify();
				} catch (Exception e) {
					// TODO: handle exception
				}finally{
					lock.unlock();
				}
			}
		}
		
	}

	public void begin(){
		final Count count = new Count();
		new Thread(new Print(count)).start();
		new Thread(new Print2(count)).start();
	}
	
	

	public static void main(String[] args) {
		new Demo().begin();
	}

}
